<template>
  <div class="p-2">
    <el-container>
      <el-main>
        <el-row :gutter="24" style="margin-top: 20px;">
          <el-col :span="4">
            <el-card>
              <el-input v-model="querySheetParams.name" @keyup.enter="getSheetList" placeholder="请输入应用名称(回车查询)" />
              <el-table
                v-loading="loadingSheetTree"
                :data="sheetList"
                row-key="sheetId"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                ref="sheetTableRef"
                :default-expand-all="isExpandAll"
                highlight-current-row
                @row-click="sheetRowClick"
              >
                <el-table-column label="应用名称" prop="name" />
              </el-table>
            </el-card>
          </el-col>

          <el-col :span="20">
            <el-card shadow="never">

              <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="字段列表" name="first">
                  <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
                    <div class="search" v-show="showSearch">
                      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                        <el-form-item label="字段名" prop="fieldName">
                          <el-input v-model="queryParams.fieldName" placeholder="请输入字段名" clearable @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="简体中文" prop="chineseName">
                          <el-input v-model="queryParams.chineseName" placeholder="请输入简体中文" clearable @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item>
                          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                      </el-form>

                      <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                          <el-button type="primary" plain icon="Plus" @click="handleBatchEdit" v-hasPermi="['system:sheetField:edit']">保存</el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </transition>

                  <el-table v-loading="loading" :data="sheetFieldList" border >
                    <el-table-column label="字段名" align="center" prop="fieldName" />
                    <el-table-column label="简体中文" align="center" prop="chineseName">
                      <template #default="scope">
                        <el-input v-model="scope.row.chineseName" placeholder="请输入简体中文" />
                      </template>
                    </el-table-column>
                    <el-table-column label="字段类型" align="center" prop="fieldType">
                      <template #default="scope">
                        <dict-tag :options="table_field_type" :value="scope.row.fieldType"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="列表排序" align="center" prop="tableSort" >
                      <template #default="scope">
                        <el-input-number v-model="scope.row.tableSort" placeholder="请输入列表排序" />
                      </template>
                    </el-table-column>
                    <el-table-column label="是否启用" align="center" prop="tableStatus">
                      <template #default="scope">
                        <el-select v-model="scope.row.tableStatus" placeholder="请选择字段是否启用">
                          <el-option
                            v-for="dict in sys_yes_no"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="列表是否显示" align="center" prop="showTable">
                      <template #default="scope">
                        <el-select v-model="scope.row.showTable" placeholder="请选择列表是否显示">
                          <el-option
                            v-for="dict in sys_yes_no"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="数据源名称" align="center" prop="dataSourceId">
                      <template #default="scope">
                        <el-select v-model="scope.row.dataSourceId" filterable clearable @change="changeTableDataSourceId($event,scope.row)" @clear="onClear($event,scope.row)" placeholder="请选择数据源类型">
                          <el-option
                            v-for="item in sheetSourceList"
                            :key="item.sheetSourceId"
                            :label="item.dataSourceName"
                            :value="item.sheetSourceId"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="字段宽度" align="center" prop="tableWidth" >
                      <template #default="scope">
                        <el-input-number v-model="scope.row.tableWidth" placeholder="请输入字段宽度" />
                      </template>
                    </el-table-column>
                    <!--<el-table-column label="表单排序" align="center" prop="formSort" >
                      <template #default="scope">
                        <el-input-number v-model="scope.row.formSort" placeholder="请输入表单排序" />
                      </template>
                    </el-table-column>
                    <el-table-column label="表单是否显示" align="center" prop="showForm">
                      <template #default="scope">
                        <el-select v-model="scope.row.showForm" placeholder="请选择表单是否显示">
                          <el-option
                            v-for="dict in sys_yes_no"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="展示方式" align="center" prop="showType">
                      <template #default="scope">
                        <el-select v-model="scope.row.showType" placeholder="请选择表单是否显示">
                          <el-option
                            v-for="dict in field_show_type"
                            :key="parseInt(dict.value)"
                            :label="dict.label"
                            :value="parseInt(dict.value)"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>-->
                    <el-table-column label="备注" align="center" prop="remark" >
                      <template #default="scope">
                        <el-input v-model="scope.row.remark" placeholder="请输入备注" />
                      </template>
                    </el-table-column>
                  </el-table>

                  <pagination
                    v-show="total>0"
                    :total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getList"
                  />
                </el-tab-pane>

                <el-tab-pane label="列表搜素配置" name="second">
                  <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
                    <div class="search" v-show="showSearch">
                      <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                          <el-button type="primary" plain icon="Plus" @click="handleSearchAdd" v-hasPermi="['system:sheetSearch:add']">新增</el-button>
                        </el-col>
                        <el-col :span="1.5">
                          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleSearchUpdate()" v-hasPermi="['system:sheetSearch:edit']">修改</el-button>
                        </el-col>
                        <el-col :span="1.5">
                          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleSearchDelete()" v-hasPermi="['system:sheetSearch:remove']">删除</el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </transition>

                  <el-table v-loading="loading" :data="sheetSearchList" @selection-change="handleSearchSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="搜索类型" align="center" prop="searchType">
                      <template #default="scope">
                        <dict-tag :options="table_search_type" :value="scope.row.searchType" />
                      </template>
                    </el-table-column>
                    <el-table-column label="搜索标题" align="center" prop="searchName" />
                    <el-table-column label="判断逻辑" align="center" prop="checkType" >
                      <template #default="scope">
                        <dict-tag :options="table_search_check" :value="scope.row.checkType" />
                      </template>
                    </el-table-column>
                    <el-table-column label="搜索字段" align="center" prop="searchFieldName" />
                    <el-table-column label="是否启用" align="center" prop="status">
                      <template #default="scope">
                        <dict-tag :options="sys_yes_no" :value="scope.row.status" />
                      </template>
                    </el-table-column>
                    <el-table-column label="高级搜索" align="center" prop="seniorSearch">
                      <template #default="scope">
                        <dict-tag :options="sys_yes_no" :value="scope.row.seniorSearch" />
                      </template>
                    </el-table-column>
                    <el-table-column label="排序" align="center" prop="sort" />
                    <!--                <el-table-column label="是否主应用" align="center" prop="isMaster">
                                      <template #default="scope">
                                        <dict-tag :options="sys_yes_no" :value="scope.row.isMaster" />
                                      </template>
                                    </el-table-column>
                                    <el-table-column label="子应用名称" align="center" prop="childSheetId" />
                                    <el-table-column label="子应用主键字段" align="center" prop="childSheetKeyId" />-->
                    <el-table-column label="数据源名称" align="center" prop="dataSourceName" />
                  </el-table>

                  <pagination
                    v-show="searchTotal>0"
                    :total="searchTotal"
                    v-model:page="querySearchParams.pageNum"
                    v-model:limit="querySearchParams.pageSize"
                    @pagination="getSheetSearchList"
                  />
                </el-tab-pane>

                <el-tab-pane label="控件配置" name="third">
                  <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
                    <div class="search" v-show="showSearch">
                      <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                          <el-button type="primary" plain icon="Plus" @click="handleButtonAdd" v-hasPermi="['system:sheetButton:add']">新增</el-button>
                        </el-col>
                        <el-col :span="1.5">
                          <el-button type="success" plain icon="Edit" @click="handleButtonAddOrUpdate()" v-hasPermi="['system:sheetButton:edit']">保存</el-button>
                        </el-col>
                        <el-col :span="1.5">
                          <el-button type="danger" plain icon="Delete" :disabled="multipleButton" @click="handleButtonDelete()" v-hasPermi="['system:sheetButton:remove']">删除</el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </transition>
                  <el-table v-loading="loading" :data="sheetButtonList" border @selection-change="handleButtonSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <!--                <el-table-column label="sheetId" align="center" prop="sheetId" />-->
                    <el-table-column label="控件名称" align="center" prop="buttonId" width="100">
                      <template #default="scope">
                        <el-select v-model="scope.row.buttonId" filterable clearable @change="changeButtonId($event,scope.row)" placeholder="请选择数据源类型">
                          <el-option
                            v-for="item in buttonList"
                            :key="item.buttonId"
                            :label="item.name"
                            :value="item.buttonId"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="控件编码" align="center" prop="buttonCode" >
                      <template #default="scope">
                        <el-input v-model="scope.row.buttonCode" placeholder="请输入控件编码" />
                      </template>
                    </el-table-column>
                    <el-table-column label="显示名称" align="center" prop="showName">
                      <template #default="scope">
                        <el-input v-model="scope.row.showName" placeholder="请输入显示名称" />
                      </template>
                    </el-table-column>
                    <el-table-column label="控件图标" align="center" prop="buttonIcon" width="100">
                      <template #default="scope">
                        <el-input v-model="scope.row.buttonIcon" placeholder="请输入控件图标,参考Element-Plus图标库" />
                      </template>
                    </el-table-column>
                    <el-table-column label="显示分组" align="center" prop="showGroup" width="150">
                      <template #default="scope">
                        <el-input v-model="scope.row.showGroup" placeholder="请输入显示分组" />
                      </template>
                    </el-table-column>
                    <el-table-column label="是否启用" align="center" prop="status" width="100">
                      <template #default="scope">
                        <el-select v-model="scope.row.status" placeholder="请选择是否启用">
                          <el-option
                            v-for="dict in sys_yes_no"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <!--                <el-table-column label="打开方式" align="center" prop="openType" width="120">
                                      <template #default="scope">
                                        <el-select v-model="scope.row.openType" placeholder="请选择打开方式">
                                          <el-option
                                            v-for="dict in sys_button_type"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="parseInt(dict.value)"
                                          ></el-option>
                                        </el-select>
                                      </template>
                                    </el-table-column>-->
                    <el-table-column label="显示位置" align="center" prop="showArea" width="120">
                      <template #default="scope">
                        <el-select v-model="scope.row.showArea" placeholder="请选择显示位置">
                          <el-option
                            v-for="dict in button_show_area"
                            :key="dict.value"
                            :label="dict.label"
                            :value="parseInt(dict.value)"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="接口域名" align="center" prop="apiDomain" width="250px"/>
                    <el-table-column label="接口地址" align="center" prop="apiUrl" width="250px">
                      <template #default="scope">
                        <el-input v-model="scope.row.apiUrl" placeholder="请输入接口地址" />
                      </template>
                    </el-table-column>
                    <el-table-column label="排序号" align="center" prop="sort" width="200">
                      <template #default="scope">
                        <el-input-number v-model="scope.row.sort" placeholder="请输入排序号"/>
                      </template>
                    </el-table-column>
                    <!--                <el-table-column label="提示" align="center" prop="tip">
                                      <template #default="scope">
                                        <el-input v-model="scope.row.tip" placeholder="请输入提示" />
                                      </template>
                                    </el-table-column>-->
                  </el-table>
                </el-tab-pane>

              </el-tabs>

            </el-card>
          </el-col>
        </el-row>

      </el-main>
    </el-container>

    <!-- 列表搜索配置弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="sheetSearchFormRef" :model="searchForm" :rules="searchRules" label-width="100px">
        <el-form-item label="搜索类型" prop="searchType">
          <el-select v-model="searchForm.searchType" filterable @change="changeCheckSearchType" placeholder="请选择搜索类型">
            <el-option
              v-for="dict in table_search_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="搜索标题" prop="searchName">
          <el-input v-model="searchForm.searchName" placeholder="请输入搜索标题" />
        </el-form-item>
        <el-form-item label="搜索提示" prop="searchTip">
          <el-input v-model="searchForm.searchTip" placeholder="请输入搜索提示" />
        </el-form-item>
        <el-form-item label="搜索字段" prop="searchFieldIds">
          <el-select v-model="searchForm.searchFieldIds" filterable clearable multiple placeholder="请选择搜索搜索字段">
            <el-option
              v-for="item in sheetFieldListAll"
              :key="item.sheetFieldId"
              :label="item.fieldName"
              :value="item.sheetFieldId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="判断逻辑" prop="checkType">
          <el-select v-model="searchForm.checkType" placeholder="请选择判断逻辑">
            <el-option
              v-for="dict in table_search_check"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据源" prop="dataSourceId" v-if="checkSearchType">
          <el-select v-model="searchForm.dataSourceId" filterable clearable @change="changeDataSourceId" placeholder="请选择数据源类型">
            <el-option
              v-for="item in sheetSourceList"
              :key="item.sheetSourceId"
              :label="item.dataSourceName"
              :value="item.sheetSourceId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择是否启用">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="高级搜索" prop="seniorSearch">
          <el-select v-model="searchForm.seniorSearch" placeholder="请选择是否高级搜索">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="是否主应用" prop="isMaster">
          <el-select v-model="searchForm.isMaster" placeholder="请选择是否主应用">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子应用" prop="childSheetId" v-if="searchForm.isMaster == 'N'">
          <el-select v-model="searchForm.childSheetId" filterable clearable @change="changeChildSheetId" placeholder="请选择子应用">
            <el-option
              v-for="item in sheetChildList"
              :key="item.sheetId"
              :label="item.name"
              :value="item.sheetId"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="searchForm.sort" placeholder="请输入排序号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitSearchForm">确 定</el-button>
          <el-button @click="cancelSearch">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="SheetField" lang="ts">
import {
  listSheetField,
  getSheetField,
  delSheetField,
  addSheetField,
  updateSheetField,
  updateBatchSheetField,
  listSheetFieldAll
} from '@/api/sheet/sheetField';
import { SheetFieldVO, SheetFieldQuery, SheetFieldForm } from '@/api/sheet/sheetField/types';
import type { TabsPaneContext } from 'element-plus'
import {SheetVO} from "@/api/sheet/sheet/types";
import {listSheet} from "@/api/sheet/sheet";
import {getSheetDataSourceBySheetId, getSheetSource} from '@/api/sheet/sheetSource';
import {SheetSourceVO} from "@/api/sheet/sheetSource/types";
import {SheetSearchForm, SheetSearchQuery, SheetSearchVO} from "@/api/sheet/sheetSearch/types";
import { addSheetSearch, delSheetSearch, getSheetSearch, listSheetSearch, updateSheetSearch} from "@/api/sheet/sheetSearch";
import { SheetButtonVO } from "@/api/sheet/sheetButton/types";
import { listAllButton } from '@/api/sheet/button';
import {ButtonVO} from "@/api/sheet/button/types";
import {listAllSheetButton, addOrUpdateSheetButton, updateSheetButton, addSheetButton} from '@/api/sheet/sheetButton';


const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { field_show_type, data_source_type, sys_yes_no, table_field_type, table_search_type, table_search_check, button_show_area, sys_button_type } = toRefs<any>(proxy?.useDict('field_show_type', 'data_source_type', 'sys_yes_no', 'table_field_type', 'table_search_type', 'table_search_check', 'button_show_area', 'sys_button_type'));

const sheetFieldList = ref<SheetFieldVO[]>([]);
const sheetFieldListAll = ref<SheetFieldVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

/** 字段列表配置 */
const initFormData: SheetFieldForm = {
  sheetFieldId: undefined,
  sheetId: undefined,
  fieldName: undefined,
  chineseName: undefined,
  fieldType: undefined,
  dataSourceType: undefined,
  dataSourceId: undefined,
  dataSourceName: undefined,
  formSort: undefined,
  tableSort: undefined,
  status: undefined,
  showTable: undefined,
  showForm: undefined,
  showType: undefined,
  remark: undefined,
}
const data = reactive<PageData<SheetFieldForm, SheetFieldQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sheetId: undefined,
    fieldName: undefined,
    chineseName: undefined,
  },
  rules: {}
});
const { queryParams, form, rules } = toRefs(data);

/** 应用搜索 */
const querySheetParams = reactive({
  name: undefined,
  pid: undefined,
})
/** 面板选中 */
const activeName = ref('first')
/** 列表树loading */
const loadingSheetTree = ref(true);
/** 是否是否展开 */
const isExpandAll = ref(false)
/** 应用列表 */
const sheetList = ref<SheetVO[]>([]);
/** 子应用列表 */
const sheetChildList = ref<SheetVO[]>([]);
/** 应用ID */
const sheetId = ref<any>("");
/** 应用数据源数据 */
const sheetSourceList = ref<SheetSourceVO[]>([]);
/** 搜索列表数据 */
const sheetSearchList = ref<SheetSearchVO[]>([]);
/** 列表搜索配置 */
const searchTotal = ref(0);
const initSearchFormData: SheetSearchForm = {
  sheetSearchId: undefined,
  sheetId: undefined,
  searchType: undefined,
  searchName: undefined,
  checkType: undefined,
  searchFieldId: undefined,
  searchFieldName: undefined,
  status: 'Y',
  seniorSearch: 'N',
  dataSourceType: undefined,
  dataSourceId: undefined,
  dataSourceName: undefined,
  isMaster: 'Y',
  childSheetId: undefined,
  childSheetKeyId: undefined,
  sort: 0,
  searchFieldIds: [],
  searchTip: undefined
}
const searchData = reactive({
  searchForm: {...initSearchFormData},
  querySearchParams: {
    pageNum: 1,
    pageSize: 10,
    sheetId: undefined
  },
  searchRules: {
    searchType: [
      { required: true, message: "请选择搜索类型", trigger: "change" }
    ],
    searchName: [
      { required: true, message: "搜索标题不能为空", trigger: "blur" }
    ],
    searchFieldId: [
      { required: true, message: "请选择搜索字段", trigger: "change" }
    ],
  }
});
const {querySearchParams, searchForm, searchRules} = toRefs(searchData);
const sheetSearchFormRef = ref<ElFormInstance>();
const checkSearchType = ref(false);
/** 列表按钮配置 */
const sheetButtonList = ref<SheetButtonVO[]>([]);
/** 控件列表 */
const buttonList = ref<ButtonVO[]>([]);
const queryButtonParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: 'Y',
})
const querySheetButtonParams = reactive({
  pageNum: 1,
  pageSize: 10,
  bindId: undefined,
  showType: 2
})
const multipleButton = ref(true);
const delButtonIds = ref<Array<string | number>>([]);

/** 查询应用字段列表 */
const getList = async () => {
  queryParams.value.sheetId = sheetId.value;
  loading.value = true;
  const res = await listSheetField(queryParams.value);
  sheetFieldList.value = res.rows;
  total.value = res.total;
  loading.value = false;

  await getSheetDataSource();
}

/** 获取所有应用字段 */
const getSheetFieldAllList = async () => {
  queryParams.value.sheetId = sheetId.value;
  const res = await listSheetFieldAll(queryParams.value);
  sheetFieldListAll.value = res.data;
}

/** 获取应用列表树 */
const getSheetList = async () => {
  loadingSheetTree.value = true;

  querySheetParams.pid = undefined;
  const res = await listSheet(querySheetParams);
  const data = proxy?.handleTree<SheetVO>(res.data, "sheetId", "pid")
  if (data) {
    sheetList.value = data
  }
  loadingSheetTree.value = false;
}

/** 获取应用子列表，只查一级 */
const getSheetChildList = async () => {
  querySheetParams.pid = sheetId.value;
  const res = await listSheet(querySheetParams);
  sheetChildList.value = res.data
}

/** 应用树点击事件 */
const sheetRowClick = (row?: SheetVO) => {
  sheetId.value = row?.sheetId;
  getList();
  getSheetFieldAllList();
  getSheetSearchList();
  getListAllSheetButton();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 面板切换事件 */
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

/** 获取应用绑定的数据源 */
const getSheetDataSource = async () => {
  const res = await getSheetDataSourceBySheetId(sheetId.value);
  sheetSourceList.value = res.data;
}

/** 数据源选择改变事件 */
const changeDataSourceId = (value: any)=>{
  sheetSourceList.value.forEach((item: any) => {
    if (item.sheetSourceId == value){
      searchForm.value.dataSourceName = item.dataSourceName;
      searchForm.value.dataSourceType = item.dataSourceType;
    }
  });
}

const changeTableDataSourceId = (value: any, row: any)=>{
  sheetSourceList.value.forEach((item: any) => {
    if (item.sheetSourceId == value){
      row.dataSourceName = item.dataSourceName;
      row.dataSourceType = item.dataSourceType;
    }
  });
}

/** 清空数据源数据 */
const onClear = (value: any, row: any) =>{
  row.dataSourceName = "";
  row.dataSourceType = "";
}

/** 保存字段列表修改 */
const handleBatchEdit = async() => {
  if (sheetId.value == ''){
    proxy?.$modal.msgError("请先选择应用");
    return;
  }
  loading.value = true;
  await updateBatchSheetField(sheetFieldList.value);
  proxy?.$modal.msgSuccess("保存成功");
  loading.value = false;
  await getList();
}

/** 搜索条件多选框选中数据 */
const handleSearchSelectionChange = (selection: SheetSearchVO[]) => {
  ids.value = selection.map(item => item.sheetSearchId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 获取搜索配置列表 */
const getSheetSearchList = async () => {
  loading.value = true;
  querySearchParams.value.sheetId = sheetId.value;
  const res = await listSheetSearch(querySearchParams.value);
  sheetSearchList.value = res.rows;
  searchTotal.value = res.total;
  loading.value = false;
}

/** 添加搜索条件表单重置 */
const resetSearch = () => {
  searchForm.value = {...initSearchFormData};
  sheetSearchFormRef.value?.resetFields();
}

/** 打开添加搜索条件弹窗 */
const handleSearchAdd = async() => {
  resetSearch();
  if (sheetId.value == ''){
    proxy?.$modal.msgError("请先选择应用");
    return;
  }
  // 获取子应用，暂只支持一级
  await getSheetChildList();

  dialog.visible = true;
  dialog.title = "添加搜索条件";
}

/** 打开修改搜索条件弹窗 */
const handleSearchUpdate = async (row?: SheetSearchVO) => {
  resetSearch();
  // 获取子应用，暂只支持一级
  await getSheetChildList();
  const _sheetSearchId = row?.sheetSearchId || ids.value[0]
  const res = await getSheetSearch(_sheetSearchId);
  Object.assign(searchForm.value, res.data);
  if (res.data.searchFieldId){
    searchForm.value.searchFieldIds = res.data.searchFieldId.split(",");
  }
  if(res.data.dataSourceId){
    checkSearchType.value = true;
  }
  dialog.visible = true;
  dialog.title = "修改搜索条件";
}

/** 删除搜索条件 */
const handleSearchDelete = async (row?: SheetSearchVO) => {
  const _sheetSearchIds = row?.sheetSearchId || ids.value;
  await proxy?.$modal.confirm('是否确认删除所选的数据项？').finally(() => loading.value = false);
  await delSheetSearch(_sheetSearchIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getSheetSearchList();
}

/** 取消按钮 */
const cancelSearch = () => {
  resetSearch();
  dialog.visible = false;
}

/** 搜索条件提交操作 */
const submitSearchForm = () => {
  sheetSearchFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      searchForm.value.sheetId = sheetId.value;
      if (searchForm.value.searchFieldIds){
        searchForm.value.searchFieldId = searchForm.value.searchFieldIds.toString();
        const arr: string[] = [];
        searchForm.value.searchFieldIds.forEach(item => {
          for (let i = 0; i < sheetFieldListAll.value.length; i++) {
            if (sheetFieldListAll.value[i].sheetFieldId == item){
              arr.push(sheetFieldListAll.value[i].fieldName)
            }
          }
        })
        searchForm.value.searchFieldName = arr.join(",");
      }
      if (searchForm.value.sheetSearchId) {
        await updateSheetSearch(searchForm.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addSheetSearch(searchForm.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("保存成功");
      dialog.visible = false;
      await getSheetSearchList();
    }
  });
}

/** 根据筛选类型是否显示选择数据源 */
const changeCheckSearchType = (value:string) => {
  const arr = ['2','3','4','5','6','7'];
  if (arr.includes(value)){
    checkSearchType.value = true;
  } else {
    checkSearchType.value = false;
    searchForm.value.dataSourceId = undefined;
    searchForm.value.dataSourceType = undefined;
    searchForm.value.dataSourceName = undefined;
  }
}

/** 设置子应用keyId */
const changeChildSheetId = (value:any) => {
    sheetChildList.value.forEach((item: any) => {
      if (item.sheetId == value){
        searchForm.value.childSheetKeyId = item.tableId;
      }
    });
}

/** 控件新增按钮 */
const random = (min:any,max:any) => Math.floor(Math.random() * (max - min + 1) + min)
const handleButtonAdd = () => {
  if (sheetId.value == ''){
    proxy?.$modal.msgError("请先选择应用");
    return;
  }
  sheetButtonList.value.push({
    sheetButtonId: '',
    bindId: sheetId.value,
    buttonId: '',
    buttonCode: '',
    buttonType: '',
    buttonIcon: '',
    showName: '',
    showGroup: '',
    showType: 2,
    openType: '',
    status: 'Y',
    showArea: '',
    apiDomain: '',
    apiUrl: '',
    showTip: '',
    sort: 0,
    random: random(0, 9999),
    isAuth: '',
    roleId: ''
  })
}

/** 控件保存按钮 */
const handleButtonAddOrUpdate = async () => {
  loading.value = true;
  await addOrUpdateSheetButton(sheetButtonList.value);
  proxy?.$modal.msgSuccess("保存成功");
  loading.value = false;
  await getListAllSheetButton();
}

/** 控件删除按钮 */
const handleButtonDelete = () => {
  console.info(delButtonIds)
  sheetButtonList.value.map((item,index)=>{
    delButtonIds.value.forEach(id =>{
      if(item.sheetButtonId == id || item.random == id){
        sheetButtonList.value.splice(index,1)
      }
    })
  })
}

/** 获取所有控件 */
const getListAllButton = async () => {
  const res = await listAllButton(queryButtonParams);
  buttonList.value = res.data;
}

/** 选择控件改变事件 */
const changeButtonId = (value: any, row: SheetButtonVO) =>{
  console.info(row)
  buttonList.value.forEach((item: any) => {
    if (item.buttonId == value){
      row.buttonCode = item.code;
      row.showName = item.name;
      row.buttonType = item.style;
      row.apiDomain = item.apiDomain;
      row.apiUrl = item.apiUrl;
    }
  });
}

/** 搜索条件多选框选中数据 */
const handleButtonSelectionChange = (selection: SheetButtonVO[]) => {
  delButtonIds.value = [];
  selection.forEach(item => {
    if (item.sheetButtonId){
      delButtonIds.value.push(item.sheetButtonId)
    } else {
      delButtonIds.value.push(item.random)
    }
  })
  multipleButton.value = !selection.length;
}

/** 获取所有应用控件 */
const getListAllSheetButton = async () => {
  querySheetButtonParams.bindId = sheetId.value;
  const res = await listAllSheetButton(querySheetButtonParams);
  sheetButtonList.value = res.data;
}

onMounted(() => {
  getSheetList();
  getListAllButton();
});
</script>
